package lhc.alg.top100;

import java.util.ArrayList;
import java.util.List;

/**
 * description: https://leetcode.cn/problems/find-all-duplicates-in-an-array/
 *  数组中重复的数据
 * author: hongchen.liao
 * date:  2022/9/4
 */
public class _442_Find_All_Duplicates_in_an_Array {

    class Solution {
        public List<Integer> findDuplicates(int[] nums) {
            int n = nums.length;
            for(int i = 0; i < n; i++){
                while(nums[i] != nums[nums[i]-1]){
                    swap(nums, i, nums[i]-1);
                }
            }
            List<Integer> ans = new ArrayList<>();
            for(int i = 0; i < n; i++){
                if(nums[i] - 1 != i){
                    ans.add(nums[i]);
                }
            }
            return ans;
        }

        void swap(int[] nums, int i, int j){
            int t = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
    }

}
